from sys import argv
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

class MyPyOpenGLTest:
    def __init__(self, width=480, height=480,
                 title='PyOpeenGL红绿蓝颜色混合效果'.encode('gbk')):
        glutInit(len(argv), argv)
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowSize(width, height)
        glutInitWindowPosition(400, 200)
        glutCreateWindow(title)
        glutDisplayFunc(self.draw)
        glutReshapeFunc(self.reshape)

        # 下面的设置会导致屏幕刷新过于频繁，暂时不用
        glutIdleFunc(self.draw)
        # 相应键盘上的非ASCII键
        glutSpecialFunc(self.special_key)

        # 初始化窗口为黑色
        glClearColor(0, 0, 0, 1)
        # 使用颜色混合，设置混合模式
        glEnable(GL_BLEND)
        glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR)

        # 切换到透视投影矩阵， 设置为单位矩阵
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        # 绿色圆盘位置
        self.green_x = -0.5
        self.green_y = 0

    def reshape(self, w, h):
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        ratio = w / h
        glViewport(0, 0, w, h)
        # 使用正交投影，设置坐标系显示范围
        gluOrtho2D(-5, 5, -5*ratio, 5*ratio);
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

    def special_key(self, key, x, y):
        # 通过上下左右按键移动绿色圆盘
        if key == GLUT_KEY_UP:
            self.green_y = self.green_y + 0.05
        elif key == GLUT_KEY_DOWN:
            self.green_y = self.green_y - 0.05
        elif key == GLUT_KEY_LEFT:
            self.green_x = self.green_x - 0.05
        elif key == GLUT_KEY_RIGHT:
            self.green_x = self.green_x + 0.05

        # 每次按键之后强制刷新屏幕
        glutPostRedisplay()
    def draw(self):

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # 当前矩阵入栈，绘制红色圆盘
        glPushMatrix()
        glTranslatef(0, 1, 0)
        glColor4f(1, 0, 0, 0.5)
        # 创建二次曲面对象
        obj = gluNewQuadric()
        # 绘制圆盘，内半径为0，外半径为1，沿Z周分片数量为30，眼半径方向分片数量为1
        gluDisk(obj, 0, 1, 30, 1)
        glPopMatrix()

        # 绘制绿色圆盘，该盘位置可通过键盘来上下移动
        glPushMatrix()
        glTranslatef(self.green_x, self.green_y, 0)
        glColor4f(0, 1, 0, 0.5)
        obj = gluNewQuadric()
        gluDisk(obj, 0, 1, 30, 1)
        glPopMatrix()

        # 绘制蓝色圆盘

        glPushMatrix()
        glTranslatef(0.5, 0, 0)
        glColor4f(0, 0, 1, 0.5)
        obj = gluNewQuadric()
        gluDisk(obj, 0, 1, 30, 1)
        glPopMatrix()

        # 交换缓冲区， 更新图形
        glutSwapBuffers()

        # 消息主循环
    def mainloop(self):
        glutMainLoop()

if __name__ == '__main__':
    MyPyOpenGLTest().mainloop()

